package com.yhq.thrift.client;

import org.apache.commons.pool2.BaseKeyedPooledObjectFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;

/**
 * Created by yanghuqiang(yhqnh@aliyun.com) on 2016/8/15.
 */
public class ThriftPoolFactory extends BaseKeyedPooledObjectFactory<ServerKey,TTransport> {

    @Override
    public void activateObject(ServerKey key, PooledObject<TTransport> p)
            throws Exception {
        p.getObject().open();
    }

    @Override
    public void destroyObject(ServerKey key, PooledObject<TTransport> p) throws Exception {
        p.getObject().close();
    }


    @Override
    public TTransport create(ServerKey key) throws Exception {
        TTransport transport = new TSocket(key.getServerHost(), key.getServerPort());
        return transport;
    }

    @Override
    public PooledObject<TTransport> wrap(TTransport value) {
        return new DefaultPooledObject<TTransport>(value);
    }
}
